<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box1,
    .box2,
    .box3 {
      position: relative;
      float: left;
      width: 500px;
      height: 300px;
      margin-left: -1px;
      margin-top: -1px;
      border: 1px solid #000;
    }

    #box1,
    #box2,
    #box3 {
      width: 200px;
      height: 200px;
    }

    /* margin自适应 */
    #box1 {
      margin: 0 auto;
      background-color: rgba(255, 0, 0, .5);
    }

    /* 子绝父相，用定位来设置 */
    #box2 {
      position: absolute;
      top: 50%;
      left: 50%;
      margin-top: -100px;
      margin-left: -100px;
      background-color: rgba(0, 255, 0, 0.5);
    }

    /* 子绝父相，用位移来设置 */
    #box3 {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background-color: rgba(0, 0, 255, 0.5);
    }
  </style>
</head>

<body>
  <div class="box1">
    <h2>方法一：</h2>
    <div id="box1"></div>
  </div>

  <div class="box2">
    <h2>方法二：</h2>
    <div id="box2"></div>
  </div>

  <div class="box3">
    <h2>方法三：</h2>
    <div id="box3"></div>
  </div>
</body>

</html>